const key = "searchHistory";
const maxLength = 15
Component({

    /**
     * 组件的属性列表
     */
    properties: {

        address: String
    },

    /**
     * 组件的初始数据
     */
    data: {

        searchHistory: []
    },

    /**
     * 组件生命周期
     */
    lifetimes: {
        attached: function () {
            let searchHistory = this._getStorage();
            this.setData({
                searchHistory
            })
        },
        detached: function () {
            // 在组件实例被从页面节点树移除时执行
        },
    },

    /**
     * 组件的方法列表
     */
    methods: {

        /**
         * 点击取消按钮
         * @param event
         */
        onCancel(event) {

            wx.navigateBack()
        },

        onConfirm(event) {

            let value = event.detail.value
            this._setStorage(value)

            this.triggerEvent("bind:confirm", event.detail)
        },

        onClick(event) {

            this.triggerEvent("bind:tagClick", event.detail)
        },

        _setStorage(value) {

            if (!value) {
                return
            }
            //获取缓存
            let storageArray = this._getStorage()
            //如无此缓存
            if (!storageArray) {
                //新建缓存为数组
                let arr = []
                arr.push(value)
                wx.setStorageSync(key, arr)

            } else {

                //小于最大个数，正常添加
                if (storageArray.length < maxLength) {

                    storageArray.unshift(value)

                } else {
                    //否则删除队尾的元素，在队头添加新元素
                    storageArray.pop()
                    storageArray.unshift(value)
                }
                wx.setStorage({
                    key: key,
                    data: storageArray
                });

            }

        },
        _getStorage() {

            return wx.getStorageSync(key);
        }

    }
})
